package com.leon.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Bean
    public PasswordEncoder creatPasswordEncoder(){return NoOpPasswordEncoder.getInstance(); }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*手动添加认证用户*//*
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("001").password(new BCryptPasswordEncoder().encode("123456")).roles("user","admin")
                .and()
                .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("user")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("user","admin","superAdmin");*/
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*未登录跳转登录页*/
        http.formLogin()
            /*.usernameParameter("userName")
            .passwordParameter("password")*/
            .loginPage("/page/login.html")
            .loginProcessingUrl("/login")
            .defaultSuccessUrl("/index.html")
            .permitAll().and().csrf().disable();

        http.authorizeRequests()
                .antMatchers("/","/img/**").permitAll()
                .antMatchers("/user/**").hasRole("user")
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/sadmin/**").hasRole("superAdmin");
        http.exceptionHandling().accessDeniedPage("/page/403.html");
    }
}
